package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.LoreDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Lore;
import com.itheima.service.LoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = LoreService.class)
@Transactional
public class LoreServiceImpl implements LoreService {

    @Autowired
    private LoreDao loreDao;

    @Override
    public void add(List<Lore> loreList) {
        if (loreList != null && loreList.size() > 0) {
            for (Lore lore : loreList) {
                Map<String,String> map = new HashMap<>();
                map.put("title",lore.getTitle());
                map.put("keyWord",lore.getKeyWord());
                Long count = loreDao.findCountByTitleAndKeyWord(map);
                if (count > 0) {
                    loreDao.edit(lore);
                } else {
                    loreDao.add(lore);
                }
            }
        }
    }

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize);
        Page<Lore> page = loreDao.selectByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }
}
